﻿package lobby
{
	import flash.display.MovieClip;
	import flash.net.NetConnection;
	import flash.events.SecurityErrorEvent;
	import flash.events.NetStatusEvent;
	import flash.events.Event;
	import flash.net.Responder;
	import flash.net.URLRequest;
	import lobby.exchangeddata.HistoryInfoBase;
	import lobby.popups.MessagePopup;
	import lobby.events.LobbyEvent;
	import flash.display.LoaderInfo;
	import lobby.exchangeddata.LobbyModel;
	import lobby.exchangeddata.LobbyUserInfo;
	import lobby.interfaces.ILanguage;
	import lobby.constants.ConstData;
	import flash.external.ExternalInterface;
	import flash.display.StageDisplayState;
	import flash.net.navigateToURL;
	import lobby.common.Utility;
	
	/**
	 * ...
	 * @author Doan Nguyen Thuy Nha Truc (Bamboo)
	 */
	public class Lobby extends MovieClip
	{
		private var loadLanguageLobby:LoadXML;
		public var formSingin:FormSingin;
		public var formLogin:FormLogin;
		public var formAgreement:FormAgreement;
		public var formMain:FormMain;
		public var messagePopup:MessagePopup;
		public var mcLoading:MovieClip;
		public var connectFMS:ConnectFMS;
		public var lobbyModel:LobbyModel;
		
		private var viewLobby:Array;
		public var currentView:ILanguage;
		public var gameLocalconnection:GameLocalConnection;
		public var currentTimeString:String; //hh_mm_ss_mmmm
		
		public function Lobby()
		{
			connectFMS = new ConnectFMS();
			lobbyModel = new LobbyModel();
			viewLobby = new Array();
			viewLobby = [formSingin, formLogin, formAgreement, formMain];
			gameLocalconnection = new GameLocalConnection();
			var mydate:Date = new Date();
			currentTimeString = mydate.getHours() + "_" + mydate.getMinutes() + "_" + mydate.getSeconds() + "_" + mydate.getMilliseconds();
			GlobalVariables.langInfo.addEventListener(LobbyEvent.HASHTABLE_COMPLETE, changeTextLanguage);
			
			this.addEventListener(LobbyEvent.CALL_LOGIN, hldLobbyEvent);
			this.addEventListener(LobbyEvent.SET_ERROR_MESSAGE, hldLobbyEvent);
			this.addEventListener(LobbyEvent.ACCEPT_AGRE, hldLobbyEvent);
			this.addEventListener(LobbyEvent.NOT_ACCEPT_AGRE, hldLobbyEvent);
			this.addEventListener(LobbyEvent.BACK_FORM_LOGIN, hldLobbyEvent);
			this.addEventListener(LobbyEvent.GET_RECENT_BET, hldLobbyEvent);
			this.addEventListener(LobbyEvent.UPDATE_HISTORY_VIEW, hldLobbyEvent);
			this.addEventListener(LobbyEvent.OPEN_SELECTED_TABLE, hldLobbyEvent);
			this.addEventListener(LobbyEvent.CALL_SHOW_LOG, hldLobbyEvent);
			this.addEventListener(LobbyEvent.CALL_SHOW_CAMERA, hldLobbyEvent);
			this.addEventListener(LobbyEvent.CALL_FULL_SCREEN, hldLobbyEvent);
			this.addEventListener(LobbyEvent.UPDATE_DATE_FROM, hldLobbyEvent);
			this.addEventListener(LobbyEvent.UPDATE_DATE_TO, hldLobbyEvent);
			this.addEventListener(LobbyEvent.GET_TRANSACTION_REPORT, hldLobbyEvent);
			this.addEventListener(LobbyEvent.UPDATE_DATE_FROM_TRANSACTION, hldLobbyEvent);
			this.addEventListener(LobbyEvent.UPDATE_DATE_TO_TRANSACTION, hldLobbyEvent);
			this.addEventListener(LobbyEvent.GET_TRANSACTION_DETAIL, hldLobbyEvent);
			this.addEventListener(LobbyEvent.CHANGE_PASS, hldLobbyEvent);
			this.addEventListener(LobbyEvent.SHOW_ERR_DATE_NULL, hldLobbyEvent);
			this.addEventListener(LobbyEvent.SHOW_ERR_CHOOSE_DATE, hldLobbyEvent);
			this.addEventListener(LobbyEvent.GET_HISTORY, hldLobbyEvent);
			this.addEventListener(LobbyEvent.SET_MENU_GAME, hldLobbyEvent);
			this.addEventListener(LobbyEvent.GET_LIST_GAME, hldLobbyEvent);
			this.addEventListener(LobbyEvent.GET_DETAIL_GAME, hldLobbyEvent);
			this.addEventListener(LobbyEvent.UPDATE_WELCOME_MASSAGE, hldLobbyEvent);
			this.addEventListener(LobbyEvent.DIALOG_RESULT_OK, hldLobbyEvent);
			this.addEventListener(LobbyEvent.SHOW_MS, hldLobbyEvent);
			
			this.connectFMS.addEventListener(LobbyEvent.SET_ERROR_MESSAGE, hldEventFMS);
			this.connectFMS.addEventListener(LobbyEvent.FAILED_LOGIN, hldEventFMS);
			this.connectFMS.addEventListener(LobbyEvent.REJECTED_LOGIN, hldEventFMS);
			this.connectFMS.addEventListener(LobbyEvent.SET_SESSION_TOKEN, hldEventFMS);
			this.connectFMS.addEventListener(LobbyEvent.SET_TABLE_LIST_BY_ACCOUNT, hldEventFMS);
			this.connectFMS.addEventListener(LobbyEvent.SET_HISTORY, hldEventFMS);
			this.connectFMS.addEventListener(LobbyEvent.UPDATE_BET_STATUS, hldEventFMS);
			this.connectFMS.addEventListener(LobbyEvent.UPDATE_HISTORY_DATE, hldEventFMS);
			this.connectFMS.addEventListener(LobbyEvent.UPDATE_HISTORY, hldEventFMS);
			this.connectFMS.addEventListener(LobbyEvent.UPDATE_REPORT_DATE, hldEventFMS);
			this.connectFMS.addEventListener(LobbyEvent.SET_TRANSACTION_REPORT, hldEventFMS);
			this.connectFMS.addEventListener(LobbyEvent.SET_TRANSACTION_REPORT_DETAIL, hldEventFMS);
			this.connectFMS.addEventListener(LobbyEvent.UPDATE_WELCOME_MESSAGE_INFO, hldEventFMS);
			this.connectFMS.addEventListener(LobbyEvent.SET_RESULT_MEMBER_INFO, hldEventFMS);
			this.connectFMS.addEventListener(LobbyEvent.SET_RESULT_MEMBER_LIMIT, hldEventFMS);
			this.connectFMS.addEventListener(LobbyEvent.SHOW_MS, hldEventFMS);
			this.connectFMS.addEventListener(LobbyEvent.GET_CURRENCY_ICON, hldEventFMS);
			this.connectFMS.addEventListener(LobbyEvent.INVALID_TOKEN, hldEventFMS);
			this.connectFMS.addEventListener(LobbyEvent.SET_HOTLINE_MSG, hldEventFMS);
			this.connectFMS.addEventListener(LobbyEvent.DELETE_HISTORY, hldEventFMS);
			
			this.lobbyModel.addEventListener(LobbyEvent.UPDATE_BET_STATUS, hldLobbyModelEvent);
			this.lobbyModel.addEventListener(LobbyEvent.UPDATE_HISTORY_DATE, hldLobbyModelEvent);
			this.lobbyModel.addEventListener(LobbyEvent.UPDATE_HISTORY, hldLobbyModelEvent);
			this.lobbyModel.addEventListener(LobbyEvent.INIT_HISTORY_COMPLETE, hldLobbyModelEvent);
			this.lobbyModel.addEventListener(LobbyEvent.UPDATE_WELCOME_MESSAGE, hldLobbyModelEvent);
			this.lobbyModel.addEventListener(LobbyEvent.UPDATE_HISTORY_VIEW, hldLobbyModelEvent);
			this.lobbyModel.addEventListener(LobbyEvent.UPDATE_DATE_REPORT, hldLobbyModelEvent);
			this.lobbyModel.addEventListener(LobbyEvent.UPDATE_TRANSACTION_REPORT, hldLobbyModelEvent);
			this.lobbyModel.addEventListener(LobbyEvent.UPDATE_TRANSFER_REPORT, hldLobbyModelEvent);
			this.lobbyModel.addEventListener(LobbyEvent.UPDATE_DETAIL_TRANSACTION_REPORT, hldLobbyModelEvent);
			
			// load in web
			this.loaderInfo.addEventListener(Event.COMPLETE, init);
		}
		
		public function getMemberWinLose():void
		{
			//trace("getMemberWinLose:" + lobbyModel.historyInfo.serverDateFrom + "-" + lobbyModel.historyInfo.serverDateTo);
			connectFMS.getMemberWinLose(lobbyModel.historyInfo.serverDateFrom, lobbyModel.historyInfo.serverDateTo);
		}
		
		private function hldLobbyModelEvent(e:LobbyEvent):void
		{
			switch (e.type)
			{
				case LobbyEvent.UPDATE_BET_STATUS: // update bet status
					showBetStatusPanel();
					break;
				case LobbyEvent.UPDATE_HISTORY_DATE: // update history date
					formMain.updateDateHistory(lobbyModel.historyInfo.serverDateFrom, lobbyModel.historyInfo.serverDateTo);
					break;
				case LobbyEvent.UPDATE_HISTORY: // update history value
					formMain.updateGameHistory(lobbyModel.historyInfo);
					break;
				case LobbyEvent.UPDATE_HISTORY_VIEW: 
					formMain.updateTableHistory(e.tableId, e.dataHis);
					break;
				case LobbyEvent.INIT_HISTORY_COMPLETE: 
					formMain.updateListCasino(lobbyModel.listCasino);
					break;
				case LobbyEvent.UPDATE_WELCOME_MESSAGE: 
					formMain.updateWelcomeMessage(lobbyModel.getWelcomeMessageInfo);
					break;
				case LobbyEvent.UPDATE_DATE_REPORT: 
					trace("chay toi roi ne");
					if (GlobalVariables.functionCallByGameDetail == "transactionReportBtn")
					{
						formMain.transactionUpdateDateReport(lobbyModel.transactionReportInfo.serverDateFrom, lobbyModel.transactionReportInfo.serverDateTo);						
						connectFMS.getTransactionReport(1, ConstData.NUM_RECORD_TRANSACTION_REPORT, lobbyModel.transactionReportInfo.serverDateFrom, lobbyModel.transactionReportInfo.serverDateTo);
						
					formMain.showTransactionReport();
					}
					else
					{
						//show transfer reports
						formMain.transferUpdateDateReport(lobbyModel.transferReportInfo.serverDateFrom, lobbyModel.transferReportInfo.serverDateTo);						
						GlobalVariables.vendorId = "-1";						
						connectFMS.getTransferReport(lobbyModel.transferReportInfo.serverDateFrom, lobbyModel.transferReportInfo.serverDateTo, GlobalVariables.vendorId, 1, ConstData.MAX_NUM_ROW_REPORT);
						
						formMain.showTransferReport();
					}
					
					break;
				case LobbyEvent.UPDATE_TRANSACTION_REPORT: 
					formMain.updateValueTransactionReport(lobbyModel.transactionReportInfo);
					break;
				case LobbyEvent.UPDATE_TRANSFER_REPORT:
						formMain.updateValueTransferReport(lobbyModel.transferReportInfo);
					break;
				case LobbyEvent.UPDATE_DETAIL_TRANSACTION_REPORT: 
					formMain.updateValueDetailTransactionReport(lobbyModel.transactionReportInfo);
					break;
			}
		}
		
		/**
		 * @author	Tom
		 */
		private function showGameHistoryPanel():void
		{
			formMain.showGameHistoryPanel();
		}
		
		/**
		 * @author	Tom
		 */
		private function showBetStatusPanel():void
		{
			formMain.updateBetStatusValue(lobbyModel.betStatusInfo);
			formMain.showBetStatusPanel();
		}
		
		private function init(e:Event):void
		{
			loadFlashVar();
			initLanguageLobby();
			activeLoading(false);
			//load logo
			formLogin.loadLogo();
			formMain.loadLogo();
			//update lang combo box
			formLogin.updateComboBox();
		}
		
		private function activeView(obj:Object):void
		{
			for (var i:uint = 0; i < viewLobby.length; i++)
			{
				if (obj == viewLobby[i])
				{
					viewLobby[i].visible = true;
					currentView = viewLobby[i];
					if (GlobalVariables.langInfo.hashTable != null)
						currentView.changeTextLang(GlobalVariables.langInfo.hashTable);
				}
				else
				{
					viewLobby[i].visible = false;
				}
			}
		}
		
		private function hldEventFMS(e:LobbyEvent):void
		{
			trace(e.type)
			switch (e.type)
			{
				case LobbyEvent.SET_SESSION_TOKEN: // update info for user
					activeLoading(false);
					updateSession(e);
					showFormAgreement();
					break;
				case LobbyEvent.FAILED_LOGIN: 
					showPopupMessage(e.result);
					break;
				case LobbyEvent.REJECTED_LOGIN: 
					showPopupMessage(e.result);
					break;
				case LobbyEvent.SET_ERROR_MESSAGE: 
					showPopupMessage(e.result);
					this.gameLocalconnection.sendLogOutMain(currentTimeString, "Logout");
					break;
				case LobbyEvent.UPDATE_BET_STATUS: 
					lobbyModel.updateRecentBet(e.result);
					break;
				case LobbyEvent.UPDATE_HISTORY_DATE: 
					lobbyModel.updateHistoryDate(e.result);
					break;
				case LobbyEvent.UPDATE_HISTORY: 
					lobbyModel.updateHistory(e.result);
					break;
				case LobbyEvent.SET_TABLE_LIST_BY_ACCOUNT: 
					lobbyModel.initListHistory(e.result);
					break;
				case LobbyEvent.SET_HISTORY: 
					lobbyModel.setHistory(e.result);
					break;
				case LobbyEvent.UPDATE_REPORT_DATE: 
					//lobbyModel.transactionReportInfo.resultServerDateTime(e.result);
					if (GlobalVariables.functionCallByGameDetail == "transactionReportBtn")
					{
					lobbyModel.transactionReportInfo.resultServerDateTime(e.result);
					}
					else
					{
						trace("vo");
						lobbyModel.transferReportInfo.resultServerDateTime(e.result);
					}
					
					break;
				case LobbyEvent.SET_TRANSACTION_REPORT: 
					trace("vo set tranction report");
					if (GlobalVariables.functionCallByGameDetail == "transactionReportBtn")
					{
					lobbyModel.transactionReportInfo.resultTransactionReport(e.result);
					}
					else
					{
						lobbyModel.transferReportInfo.resultTransferReport(e.result);
					}					
					break;
				case LobbyEvent.SET_TRANSACTION_REPORT_DETAIL: 
					trace("vo set tranction report detail");
					lobbyModel.transactionReportInfo.resultDetailTransactionReport(e.result);
					break;
				case LobbyEvent.SET_RESULT_MEMBER_LIMIT: 
					lobbyModel.userInfo.resultSetLimit(e.result);
					break;
				case LobbyEvent.SET_RESULT_MEMBER_INFO: 
					formMain.updateUserInfo(e.result);
					lobbyModel.userInfo.resultSetMemberInfo(e.result);
					break;
				case LobbyEvent.UPDATE_WELCOME_MESSAGE_INFO: 
					lobbyModel.updateWelComeMessage(e.result);
					break;
				case LobbyEvent.SHOW_MS: 
					showPopupMessage(e.ms);
					break;
				case LobbyEvent.GET_CURRENCY_ICON: 
					formMain.getCurrentIcon(e.result);
					break;
				case LobbyEvent.INVALID_TOKEN:
					showPopupMessage(e.ms);
					this.gameLocalconnection.sendLogOutMain(currentTimeString, "Logout");
					break;
				case LobbyEvent.SET_HOTLINE_MSG:
					formMain.showHotlinePanel();
					break;
				case LobbyEvent.DELETE_HISTORY:
					lobbyModel.updateHistoryByCancelGame(e.tableId);
					formMain.deleteTableHistory(e.tableId);
					break;
					
			}
		}
		
		private function showFormAgreement():void
		{
			activeView(formAgreement);
			var pathText:String = GlobalVariables.lang + "_" + "agreement.txt";
			formAgreement.loadTxt(pathText);
		}
		
		private function updateSession(e:LobbyEvent):void
		{
			lobbyModel.userInfo.init(GlobalVariables.userName);
			
			lobbyModel.updateSetSessionToken(e.result);
			connectFMS.setSessionId = lobbyModel.getSessionId;
			connectFMS.getPersonInfo(lobbyModel.getSessionId);
			connectFMS.getMemberLimit(lobbyModel.getSessionId);
			connectFMS.getAccInfoByUserN(lobbyModel.getSessionId, GlobalVariables.userName);
			connectFMS.getListDepWithVen(lobbyModel.getSessionId, GlobalVariables.userName);
		}
		
		private function changeTextLanguage(e:LobbyEvent):void
		{
			currentView.changeTextLang(GlobalVariables.langInfo.hashTable);
			messagePopup.changeTextLang(GlobalVariables.langInfo.hashTable);
		}
		
		private function hldLobbyEvent(e:LobbyEvent):void
		{
			switch (e.type)
			{
				case LobbyEvent.CALL_LOGIN: // goi ham login
					doLogin();
					break;
				case LobbyEvent.SET_ERROR_MESSAGE: 
					showPopupMessage(e.result);
					break;
				case LobbyEvent.BACK_FORM_LOGIN: // khoi tao lai cac thong so login
					backLogin();
					break;
				case LobbyEvent.NOT_ACCEPT_AGRE: // khoi tao lai cac thong so login
					backLogin();
					break;
				case LobbyEvent.ACCEPT_AGRE: // qua formMain, goi một số thông tin tao menu, load casino,...
					connectFMS.getTableListByAccount(connectFMS.getSessionId, GlobalVariables.tablefilter);
					showFormMain();
					break;
				case LobbyEvent.SET_SESSION_TOKEN: // update thong tin user
					break;
				case LobbyEvent.GET_RECENT_BET: // update bet status
					connectFMS.getRecentBet("1", uint(e.ms), ConstData.NUM_PER_PAGE);
					break;
				case LobbyEvent.UPDATE_HISTORY_VIEW: 
					connectFMS.getHistoryByTable(e.tableId, e.gameType);
					break;
				case LobbyEvent.OPEN_SELECTED_TABLE: 
					trace("Open selected table : " + e.tableId + " : " + e.casinoID);
					GlobalVariables.roomId = e.tableId;
					GlobalVariables.casinoId = e.casinoID;
					trace("Open selected table : " + GlobalVariables.roomId);
					
					closeFullScreen();
					
					receiveConnection();
					break;
				case LobbyEvent.CALL_SHOW_LOG: 
					closeFullScreen();
					var url:String = GlobalVariables.urlLog.replace("{0}", GlobalVariables.userName);
					var langCode:String = Utility.convertLanguageCode(GlobalVariables.lang);
					url = url.replace("{1}", langCode);
					url = url.replace("amp;", "&");
					var showLogURL:URLRequest = new URLRequest(url);
					navigateToURL(showLogURL);
					break;
				case LobbyEvent.CALL_SHOW_CAMERA: 
					closeFullScreen();
					var showCameraURL:URLRequest = new URLRequest("CameraDetail.aspx");
					navigateToURL(showCameraURL);
					break;
				case LobbyEvent.CALL_FULL_SCREEN: 
					trace(stage.displayState)
					if (stage.displayState == StageDisplayState.FULL_SCREEN)
					{
						stage.displayState = StageDisplayState.NORMAL;
					}
					else if (stage.displayState == StageDisplayState.NORMAL)
					{
						stage.displayState = StageDisplayState.FULL_SCREEN;
					}
					break;
				case LobbyEvent.UPDATE_DATE_FROM: 
					lobbyModel.historyInfo.serverDateFrom = formMain.sendDateHistoryInfo(1);
					break;
				case LobbyEvent.UPDATE_DATE_TO: 
					lobbyModel.historyInfo.serverDateTo = formMain.sendDateHistoryInfo(2);
					break;
				case LobbyEvent.UPDATE_DATE_FROM_TRANSACTION: 
					if (GlobalVariables.functionCallByGameDetail == "transactionReportBtn")
					{
					lobbyModel.transactionReportInfo.serverDateFrom = formMain.sendDateTransactionInfo(1);
					}
					else
					{
						lobbyModel.transferReportInfo.serverDateFrom = formMain.sendDateTransferInfo(1);
					}
					break;
				case LobbyEvent.UPDATE_DATE_TO_TRANSACTION: 
					if (GlobalVariables.functionCallByGameDetail == "transactionReportBtn")
					{
					lobbyModel.transactionReportInfo.serverDateTo = formMain.sendDateTransactionInfo(2);
					}
					else
					{
						lobbyModel.transferReportInfo.serverDateFrom = formMain.sendDateTransferInfo(2);
					}
					break;
				case LobbyEvent.GET_TRANSACTION_REPORT: 
					if (GlobalVariables.functionCallByGameDetail == "transactionReportBtn")
					{
						connectFMS.getTransactionReport(uint(e.ms), ConstData.NUM_RECORD_TRANSACTION_REPORT, lobbyModel.transactionReportInfo.serverDateFrom, lobbyModel.transactionReportInfo.serverDateTo);
					}
					else
					{
						connectFMS.getTransferReport(lobbyModel.transferReportInfo.serverDateFrom, lobbyModel.transferReportInfo.serverDateTo, GlobalVariables.vendorId, uint(e.ms), ConstData.MAX_NUM_ROW_REPORT);
					}					
					break;
				case LobbyEvent.GET_TRANSACTION_DETAIL: 
					lobbyModel.transactionReportInfo.transId = e.ms;
					connectFMS.getDetailTransactionRpt(uint(e.ms));
					break;
				case LobbyEvent.CHANGE_PASS: 
					trace("setNewPassword:" + lobbyModel.userInfo.oldPass + ":::" + lobbyModel.userInfo.newPass);
					connectFMS.setNewPass(lobbyModel.userInfo.oldPass, lobbyModel.userInfo.newPass);
					break;
				case LobbyEvent.SHOW_ERR_DATE_NULL: 
					showPopupMessage("PleaseInputDate");
					break;
				case LobbyEvent.SHOW_ERR_CHOOSE_DATE: 
					showPopupMessage("DateRangeNAN");
					break;
				case LobbyEvent.GET_HISTORY: 
					connectFMS.getMemberWinLose(lobbyModel.historyInfo.serverDateFrom, lobbyModel.historyInfo.serverDateTo);
					break;
				case LobbyEvent.SET_MENU_GAME: 
					menuGameHdl(e.ms);
					break;
				case LobbyEvent.GET_LIST_GAME: 
					//get game
					var listGame:Array = new Array()
					listGame = lobbyModel.getGameTypeInCasino(e.casinoID);
					formMain.getListGameCasino(listGame);
					
					var tablesList:Array = lobbyModel.getTablesCasino(e.casinoID);
					formMain.loadTables(tablesList);
					break;
				case LobbyEvent.GET_DETAIL_GAME: 
					var tablesList1:Array = lobbyModel.getTablesInGameTypeInCasion(e.gameType, e.casinoID);
					formMain.loadTables(tablesList1);
					break;
				case LobbyEvent.UPDATE_WELCOME_MASSAGE: 
					connectFMS.callGetWelcomeMessage();
					break;
				case LobbyEvent.DIALOG_RESULT_OK:
					hdlDialogResult(e.result);
					break;				
				case LobbyEvent.SHOW_MS:
					showPopupMessage(e.ms);
					break;
			}
		}
		
		/**
		 * @author	Tom
		 * @param	result
		 */
		private function hdlDialogResult(result:String):void 
		{
			//trace("hdlDialogResult",result);
			switch(result)
			{
				case "IdPwdMismatch":
				case "RepeatedLogin":
				case "Token Invalid":
				case "IdNoAccessRights":
					backLogin();
					break;
			}
		}
		
		private function menuGameHdl(e:String):void
		{
			trace("menuGameHdl:" + e);
			GlobalVariables.functionCallByGameDetail = e;
			var arrTemp:Array;
			switch (e)
			{
				case "lobbyBtn": 
					trace("thoat");
					/*stage.displayState = StageDisplayState.NORMAL;
					   ExternalInterface.call("CloseBrowser");
					 this.loadGameFirst.unloadSwf();*/
					break;
				case "accountInfoBtn": 
					formMain.updateAccountInfoValue(lobbyModel.userInfo);
					formMain.showAccountInfoPanel();
					break;
				case "betStatusBtn": 
					connectFMS.getRecentBet("1", 1, ConstData.NUM_PER_PAGE);
					break;
				case "transactionReportBtn": 
				case "trasferReportBtn": 
					connectFMS.getServerDate();
					break;
				case "gameHistoryBtn": 
					connectFMS.getServerDate();
					formMain.showGameHistoryPanel();
					break;
				case "gameRuleBtn": 
					formMain.showGameRulePanel();
					break;
				case "supportBtn": 
					connectFMS.getHotLineMsg();
					break;
			}
		}
		
		private function receiveConnection()
		{
			var listGameSend_arr:Array = new Array();
			var listGameName_arr:Array = new Array();
			var statusGame_arr:Array = new Array();			
			
			//var _arr:Array = lobbyModel.getTablesCasino(GlobalVariables.casinoId);
			var _arr:Array = new Array();
			var bacArr:Array = new Array();
			var bacInsArr:Array = new Array();
			if (GlobalVariables.casinoId == "2") {
				bacArr = lobbyModel.getTablesInGameTypeInCasion("Ba", GlobalVariables.casinoId);
				_arr = bacArr;
				bacInsArr = lobbyModel.getTablesInGameTypeInCasion("Bi", GlobalVariables.casinoId);
				for (var zz = 0; zz < bacInsArr.length; zz++) {
					_arr.push(bacInsArr[zz]);
				}
			}else {
				_arr = lobbyModel.getTablesInGameTypeInCasion("Ba", GlobalVariables.casinoId);
			}
			
			gameLocalconnection.closeConnect();
			//gameLocalconnection = new GameLocalConnection();
			var mydate:Date = new Date();
			currentTimeString = mydate.getHours() + "_" + mydate.getMinutes() + "_" + mydate.getSeconds() + "_" + mydate.getMilliseconds();
			trace("_arr.length : " + _arr.length);
			for (var i = 0; i < _arr.length; i++)
			{
				trace("----------- : " + _arr[i]);
				var obj:HistoryInfoBase = HistoryInfoBase(_arr[i]);
				//trace(obj.getTableClose, obj.getTableId, obj.getTableName);
				listGameSend_arr.push(obj.getTableId);
				statusGame_arr.push(obj.getTableClose);
				listGameName_arr.push(obj.getTableName);
			}
			var gameType:String = "BAC";
			if (GlobalVariables.roomId == "18" || GlobalVariables.roomId == "23" || GlobalVariables.roomId == "24")
			{
				gameType = "BACINS";
			}
			GlobalVariables.dynamicLobby = createDynamicLobby(listGameSend_arr, listGameName_arr);
			trace("khaiiiiiiiiiiiiiiii : " + GlobalVariables.roomId);
			if (GlobalVariables.roomId == "3bac")
			{
				var listGameSend3Bac:String = filterTables(listGameSend_arr);
				var tmpStrCloseTb3Bac:String = statusGame3Bac(listGameSend_arr, statusGame_arr);
				listGameSend3Bac = listGameSend3Bac + "@" + tmpStrCloseTb3Bac;
				trace("vo 3bac : " + listGameSend3Bac);
				ExternalInterface.call("checkLoadGamedetail3BAC('" + currentTimeString + "','" + listGameSend3Bac + "')");
			}
			else if (GlobalVariables.casinoId == "12" || GlobalVariables.roomId == "20" || GlobalVariables.roomId == "21" ||
					 GlobalVariables.roomId == "22" || GlobalVariables.roomId == "23" || GlobalVariables.roomId == "24")
			{	
				var tmpStrCloseTb:String = "";
				var typeGameSend:String = "";
				tmpStrCloseTb = statusGame(statusGame_arr);
				typeGameSend = reNameGameType(listGameSend_arr)
				var listGameSend:String = listGameSend_arr.join(",");
				listGameSend = typeGameSend + "@" + listGameSend + "@" + tmpStrCloseTb;
				
				trace("vo HL : " + listGameSend);
				ExternalInterface.call("loadGameDetailBigBac('" + currentTimeString + "','" + listGameSend + "','" + gameType + "')");
			}
			else
			{
				trace("vo thuong");
				//grand golden
				var arr_grand:Array = lobbyModel.getTablesCasino("2");
				
				//lucky
				var arr_lucky:Array = lobbyModel.getTablesCasino("0");
				//89
				var arr_89:Array = lobbyModel.getTablesCasino("1");
				trace("arr_grand : " + arr_grand.length + " : " + arr_lucky.length + " : " + arr_89.length);
				
				
				GlobalVariables.dynamicLobby = createAs2DynamicLobby(arr_grand, arr_lucky, arr_89);
				//ExternalInterface.call("alertScript", "GlobalVariables.dynamicLobby : " + GlobalVariables.dynamicLobby);
				trace("GlobalVariables.dynamicLobby : " + GlobalVariables.dynamicLobby);
				ExternalInterface.call("checkLoadGamedetail('" + currentTimeString + "')");
			}
			this.gameLocalconnection.init("fromGameDetail" + currentTimeString, "fromMain" + currentTimeString);
		}
		private function filterTables(listGameSend_arr:Array):String {
			var filter_arr:Array = new Array();
			var _str:String = "";
			for (var i = 0; i < listGameSend_arr.length; i++) {
				if (listGameSend_arr[i] != "56" && listGameSend_arr[i] != "57" && listGameSend_arr[i] != "58" &&
				    listGameSend_arr[i] != "59" && listGameSend_arr[i] != "60") {
					filter_arr.push(listGameSend_arr[i]);
					
				}
				if (i == (listGameSend_arr.length - 1)) {
					_str =  filter_arr.join(",");
				}
			}	
			return _str;
		}
		
		private function createAs2DynamicLobby(arr_grand:Array, arr_lucky:Array, arr_89:Array):String {
			var _str1:String = "";
			var _str2:String = "";
			var _str3:String = "";
			var _str:String = "";
			if (arr_grand.length > 0) {
				for (var i = 0; i < arr_grand.length; i++) {	
					trace("cuiiiiii : " + arr_grand[i].getTableId);
					if (arr_grand[i].getTableId != "20" && arr_grand[i].getTableId != "21" && arr_grand[i].getTableId != "22" &&
						arr_grand[i].getTableId != "23" && arr_grand[i].getTableId != "24") {
						_str1 += arr_grand[i].getTableId + "@" + arr_grand[i].getTableName + "#";
					}					
				}
			}
			if (arr_lucky.length > 0) {
				for (var j = 0; j < arr_lucky.length; j++) {
					_str2 += arr_lucky[j].getTableId + "@" + arr_lucky[j].getTableName + "#";
				}
			}
			if (arr_89.length > 0) {
				for (var k = 0; k < arr_89.length; k++) {
					_str3 += arr_89[k].getTableId + "@" + arr_89[k].getTableName + "#";
				}
			}
			
			trace("_str thường : " + _str1 + " : " + _str2 + " : " + _str3);
			_str = _str1 + _str2 + _str3;
			_str = _str.substr(0, _str.length - 1);
			trace(_str);
			return _str;
			/*_str = _str2 + _str3;
			_str = _str.substr(0, _str.length - 1);
			return _str;*/
		}
		
		private function createDynamicLobby(gameID:Array, gameName:Array):String
		{
			var _str:String = "";
			trace("dynamic : " + gameID);
			for (var i = 0; i < gameID.length; i++)
			{
				if ((gameID[i] == "20" || gameID[i] == "21" || gameID[i] == "22" ||
					gameID[i] == "23" || gameID[i] == "24" ||
				    gameID[i] == "50" || gameID[i] == "51" || gameID[i] == "52" || gameID[i] == "53" || 
				   gameID[i] == "54" || gameID[i] == "55" || gameID[i] == "56" || gameID[i] == "57" || 
				   gameID[i] == "58" || gameID[i] == "59" || gameID[i] == "60") && (GlobalVariables.roomId != "3bac")){	
					if (i == (gameID.length - 1)) {	
						if (gameID[i] == "23" || gameID[i] == "24") {
							_str += gameID[i] + "@" + gameName[i]+"@BACINS";
						}else if (gameID[i] == "20" || gameID[i] == "21" || gameID[i] == "22" ||
							gameID[i] == "50" || gameID[i] == "51" || gameID[i] == "52" || 
						   gameID[i] == "53" || gameID[i] == "54" || gameID[i] == "55") {
							_str += gameID[i] + "@" + gameName[i]+"@BAC";
						}else {
							_str += gameID[i] + "@" + gameName[i]+"@BACTELE";
						}
					} else {
						if (gameID[i] == "23" || gameID[i] == "24") {
							_str += gameID[i] + "@" + gameName[i]+"@BACINS#";
						}else if (gameID[i] == "20" || gameID[i] == "21" || gameID[i] == "22" ||
							gameID[i] == "50" || gameID[i] == "51" || gameID[i] == "52" || 
						   gameID[i] == "53" || gameID[i] == "54" || gameID[i] == "55") {
							_str += gameID[i] + "@" + gameName[i] + "@BAC#";
						}else {
							_str += gameID[i] + "@" + gameName[i] + "@BACTELE#";
						}
					}
				}else{
					if (i == (gameID.length-1)) {
						_str += gameID[i] + "@" + gameName[i];
					} else {
						_str += gameID[i] + "@" + gameName[i] + "#";
					}
				}
				
				
				/*if (i == (gameID.length - 1))
				{
					_str += gameID[i] + "@" + gameName[i];
				}
				else
				{
					_str += gameID[i] + "@" + gameName[i] + "#";
				}*/
			}
			trace("ket thuc : " + _str);
			return _str;
		}
		
		private function statusGame3Bac(listGameSend_arr:Array, statusGame_arr:Array):String
		{
			var ArrStatus:Array = new Array();
			var _str:String = "";
			for (var i = 0; i < statusGame_arr.length; i++)
			{
				if (listGameSend_arr[i] != "56" && listGameSend_arr[i] != "57" && listGameSend_arr[i] != "58" &&
				    listGameSend_arr[i] != "59" && listGameSend_arr[i] != "60") {
						if (statusGame_arr[i] == false)
						{
							ArrStatus.push("open");
						}
						else
						{
							ArrStatus.push("close");
						}
					}				
				
				if (i == (statusGame_arr.length - 1))
				{
					_str = ArrStatus.join(",");
				}
			}
			return _str;
		}
		
		private function statusGame(statusGame_arr:Array):String
		{
			var ArrStatus:Array = new Array();
			var _str:String = "";
			for (var i = 0; i < statusGame_arr.length; i++)
			{
				if (statusGame_arr[i] == false)
				{
					ArrStatus.push("open");
				}
				else
				{
					ArrStatus.push("close");
				}
				
				if (i == (statusGame_arr.length - 1))
				{
					_str = ArrStatus.join(",");
				}
			}
			return _str;
		}
		
		private function reNameGameType(listGameSend_arr:Array):String
		{
			var ArrName:Array = new Array();
			var _str:String = "";
			for (var i = 0; i < listGameSend_arr.length; i++)
			{
				trace("lam lai : " + listGameSend_arr[i]);
				if (listGameSend_arr[i] == "23" || listGameSend_arr[i] == "24") {
					ArrName.push("BACINS");
				}else if (listGameSend_arr[i] == "20" || listGameSend_arr[i] == "21" || listGameSend_arr[i] == "22" ||
					listGameSend_arr[i] == "50" || listGameSend_arr[i] == "51" || listGameSend_arr[i] == "52" || 
					listGameSend_arr[i] == "53" || listGameSend_arr[i] == "54" || listGameSend_arr[i] == "55")
				{
					ArrName.push("BAC");
				}
				else
				{
					ArrName.push("BACTELE");
				}
				if (i == (listGameSend_arr.length - 1))
				{
					_str = ArrName.join(",");
				}
			}
			return _str;
		
		}
		
		private function showFormMain():void
		{
			activeView(formMain);
			formMain.updateComboBox();
			connectFMS.callGetWelcomeMessage();
		}
		
		private function backLogin():void
		{
			if (GlobalVariables.singin)
			{
				activeView(formSingin);
				ExternalInterface.call("closeWindow()");
			}
			else
			{
				activeView(formLogin);
			}
			
			formLogin.resetText();
			formLogin.updateComboBox();
			connectFMS.closeConnect();
		}
		
		private function doLogin():void
		{
			initFmsInfo();
			connectFMS.getConnect();
			activeLoading(true);
		}
		
		/**
		 * Function calling when you run in web
		 * Ham nay can kiem tra lai, chua check co du thong tin chua
		 * @param	e
		 */
		private function loadFlashVar():void
		{
			try
			{
				var paramObj:Object = LoaderInfo(root.loaderInfo).parameters;
				if (paramObj["rtmp"] != null)
					GlobalVariables.rtmpStr = paramObj["rtmp"];
				if (paramObj["VodRtmp"] != null)
					GlobalVariables.vodRtmp = paramObj["VodRtmp"];
				if (paramObj["VPN"] != null)
					GlobalVariables.vpn = paramObj["VPN"];
				if (paramObj["LangJ"] != null)
					GlobalVariables.lang = paramObj["LangJ"];
				if (paramObj["siteName"] != null)
					GlobalVariables.siteName = paramObj["siteName"];
				if (paramObj["SubDomain"] != null)
					GlobalVariables.subDomain = paramObj["SubDomain"];
				if (paramObj["fmsVideo"] != null)
					GlobalVariables.fmsVideo = paramObj["fmsVideo"];
				if (paramObj["HidePassword"] != null)
					GlobalVariables.hidePassword = paramObj["HidePassword"];
				if (paramObj["fmsMonitor"] != null)
					GlobalVariables.fmsMonitor = paramObj["fmsMonitor"];
				if (paramObj["Limelight"] != null)
					GlobalVariables.limelight = paramObj["Limelight"];
				if (paramObj["choiceMenu"] != null)
					GlobalVariables.choiceMenu = paramObj["choiceMenu"];
				if (paramObj["ip"] != null)
					GlobalVariables.ip = paramObj["ip"];
				if (paramObj["countrycode"] != null)
					GlobalVariables.countryCode = paramObj["countrycode"];
				if (paramObj["UrlLog"] != null)
					GlobalVariables.urlLog = paramObj["UrlLog"];
				if (paramObj["showTransfer"] != null)
					GlobalVariables.showTransfer = paramObj["showTransfer"];
				if (paramObj["tablefilter"] != null)
					GlobalVariables.tablefilter = paramObj["tablefilter"];
				if (paramObj["gmgdomain"] != null)
					GlobalVariables.gmgdomain = paramObj["gmgdomain"];
				/////////check for singIn
				if (paramObj["userId"] != null)
				{
					GlobalVariables.userName = paramObj["userId"];
					GlobalVariables.singin = true;
				}
				if (paramObj["pass"] != null)
					GlobalVariables.pass = paramObj["pass"];
				if (paramObj["userType"] != null)
					GlobalVariables.userType = paramObj["userType"];
				if (paramObj["preUserId"] != null)
					GlobalVariables.preUserId = paramObj["preUserId"];
				if (paramObj["parentsid"] != null)
					GlobalVariables.parentSID = paramObj["parentsid"];
				if(GlobalVariables.singin)
				{
					//goto signIn, it mean go to agreement
					activeView(formSingin);
					doLogin();
				}
				else
				{
					//goto form login
					activeView(formLogin);
				}
			}
			catch (e:Error)
			{
				trace(e.message)
			}
		
		}
		
		/**
		 * Can kiem tra lai du thong so login chua
		 */
		private function initFmsInfo():void
		{
			connectFMS.setFmsPath = GlobalVariables.rtmpStr;
			connectFMS.setLanguage = GlobalVariables.lang;
			connectFMS.setNcName = GlobalVariables.siteName;
			connectFMS.setVersionNo = GlobalVariables.versionNo;
			connectFMS.setIp = GlobalVariables.ip;
			connectFMS.setCountryCode = GlobalVariables.countryCode;
			connectFMS.setLoginTypeId = GlobalVariables.loginTypeId;
			connectFMS.setParentSID = GlobalVariables.parentSID;
			//connectFMS.setRoomId = GlobalVariables.roomId;
			connectFMS.setUserId = GlobalVariables.userName;
			connectFMS.setUserPassword = GlobalVariables.pass;
			connectFMS.setUserType = GlobalVariables.userType;
			connectFMS.setSessionId = GlobalVariables.sessionId;
			//connectFMS.setCasinoId = GlobalVariables.casinoId;
			connectFMS.setSiteName = GlobalVariables.siteName;
			connectFMS.setIsMain = GlobalVariables.isMain;
		}
		
		private function initLanguageLobby():void
		{
			this.loadLanguageLobby = new LoadXML();
			this.loadLanguageLobby.loadData("menuMain.xml");
			this.loadLanguageLobby.addEventListener(LobbyEvent.LOAD_XML_COMPLETE, loadLanguageInfoHdl);
		}
		
		private function loadLanguageInfoHdl(e:LobbyEvent):void
		{
			GlobalVariables.langInfo.updateInfo(this.loadLanguageLobby.xmlNode, GlobalVariables.lang);
		}
		
		/**
		 * @author	Tom
		 */
		private function showPopupMessage(msgCode:String):void
		{
			trace("showPopupMessage" + msgCode)
			messagePopup.setMsgCode = msgCode;
			messagePopup.showMessage(GlobalVariables.langInfo.hashTable.lookupString(msgCode));
			activeLoading(false);
		}
		
		/**
		 * @author	Bamboo
		 * @param	value
		 * @usage	show loading
		 */
		public function activeLoading(value:Boolean)
		{
			this.mcLoading.visible = value;
		}
		
		private function closeFullScreen():void {
			if (stage.displayState == StageDisplayState.FULL_SCREEN)
			{
				stage.displayState = StageDisplayState.NORMAL;
			}
		}
	}

}